--[[
FilePath: \Lua\View\UIActivityExplor\UIExplorShop.lua
游园活动兑换
--]]

require 'View/UIBase/UIBase'

UIExplorShop = UIBase.New(PanelNames.UIExplorShop)
local _M = UIExplorShop

_M.hasInit = false
_M.ContentItems = {}
_M.activeId = nil

function _M.Init(func, id)
    _M.activeId = id
    UIBase.Init(_M, func)
end

function _M:OnCreate()
    if not _M.hasInit then
        self:RegisterOnClick(self:GetChild("Btn_BgClose"), self.OnBack)
        self.title = self:GetChild("Text_Title");
        self.itemList = self:GetChild("List_Goods");
        self.CashLb = self:GetChild("Bar_Res");
        self.tipTime = self:GetChild("Text_CountDown");
        _M.hasInit = true

        self.itemList.itemRenderer = self.RefreshItem;
        self:addEvent()
    end
end

function _M:addEvent()
    self:RegisterEvent(Config.EventType.Fresh_Active,self.Refresh);
    --self.btnHelp.onClick:Add(self.HelpTip, self)
end

function _M:removeEvent()
    --self.btnHelp.onClick:Remove(self.HelpTip)
end

function _M:HelpTip()
    if self.tableData ~= nil and self.tableData.f_ExplainTitle ~= nil and self.tableData.f_ExplainText ~= nil then
        logicMgr.UIShowManager.ShowCommonTips(tostring(self.tableData.f_ExplainTitle), tostring(self.tableData.f_ExplainText));
    end
end

-- 显示
function _M:OnEnable()
    self:Refresh();
    logicMgr.HeroManager.setGetNewHeroShow(true);
    if self.activeId ~= nil then
        logicMgr.ActiveManager.updateActiveOpenStatus(self.activeId);
    end
end

_M.itemConfig = nil;
_M.serverDataTab = nil;
function _M:Refresh()
    if self.activeId == nil or not _M.hasInit then
        self:OnBack();
        return;
    else
        self.tableData, self.serverData = logicMgr.ActiveManager.getActiveData(self.activeId);
        if self.serverData == nil then
            self:OnBack();
            return;
        end
    end

    self.serverDataTab = nil;
    if self.itemConfig == nil then
        self.itemConfig = {};
        local config = G.dataTable[tostring(self.tableData.f_ItemTableName)];
        for k, v in pairs(config) do
            if tonumber(v.f_ActivityId) == tonumber(self.activeId) and logicMgr.CostManager.isOpenItem(v) then
                table.insert(self.itemConfig, v)
            end
        end
    end

    table.sort(self.itemConfig, function(a, b)
        local numA, stateA = self:GetServerData(a);
        local numB, stateB = self:GetServerData(b);
        if stateA > stateB then
            return true;
        end
        if stateA < stateB then
            return false;
        end
        return a.f_Id < b.f_Id;
    end)

    self.itemList.numItems = #self.itemConfig;
    --if self.playEffect then
    --    self.itemList:ScrollToView(0);
    --    self.playEffect = false;
    --    HelperFunc.ListTranstionPlay(self.itemList)
    --end
    self.title.text = getLanguage(self.tableData.f_ActivityName);
    local costItemId = decodeJsonStrToTabel(self.tableData.f_CostItemId);
    local costId = tonumber(costItemId[1]);
    self.CashLb.icon = EnumConst.AtlasPath.ItemAtlas .. G.dataTable["t_item"][tostring(costId)].f_Icon;
    local haveNum = logicMgr.ItemManager.getBagNumByTableID(costId);
    self.CashLb.title = haveNum;

    local time = HelperFunc.GetServerTime();
    self.endCountDown = self.serverData.endTime - time;
    self:updateActiveCountDown();
    self:TimeCall(self.updateActiveCountDown, 1000, -1);
end

function _M:updateActiveCountDown()
    if self.endCountDown == nil then
        return;
    end
    local showTimeTips = self.tipTime
    if self.showTimeMode == 2 then
        showTimeTips = self.txtChunjieTips
    end
    if self.endCountDown <= 0 then
        showTimeTips.text =  getLanguage("Sys_ActivityEnd");
        self:RemoveTimeCall(self.updateActiveCountDown)
    else
        showTimeTips.text = string.format(getLanguage("ActivityExplorTips09"), HelperFunc.GetSurpTimeStr2(self.endCountDown));
    end
    self.endCountDown = self.endCountDown - 1;
end

function _M.RefreshItem(index, itemObj)
    _M:CreateItem(index, itemObj)
    local config = _M.itemConfig[index + 1];
    local num, state = _M:GetServerData(config);
    _M.ContentItems[index]:OnShow(config, num)
end

function _M:OnCheckStateChange()
    if _M.ctr_check.selectedIndex == 1 then
        _M.ctr_check.selectedIndex = 0
        logicMgr.ActiveManager.ExchangeSetRedDot(0)
    else
        _M.ctr_check.selectedIndex = 1
        logicMgr.ActiveManager.ExchangeSetRedDot(1)
    end
end

function _M:GetServerData(config)
    if self.serverData == nil then
        return 0, -1;
    end
    local num;
    if self.serverData.param ~= nil and self.serverData.param.buyCountMap ~= nil then
        num = self.serverData.param.buyCountMap[tostring(config.f_Id)];
    end
    if num == nil then
        num = 0;
    end
    if tonumber(num) >= tonumber(config.f_Limit) then
        return num, -1;
    else
        if tonumber(config.f_Sort) == 2 then
            return num, 2;
        end
        local costItem = decodeJsonStrToTabel(config.f_CostList)
        local engNum = 0;
        for i = 1, #costItem do
            local haveNum = logicMgr.ItemManager.getBagNumByTableID(tonumber(costItem[i][1]));
            local costNum = costItem[i][2];
            if tonumber(haveNum) >= tonumber(costNum) then
                engNum = engNum + 1;
            end
        end
        if engNum == #costItem and tonumber(config.f_Sort) ~= 0 then
            return num, 1;
        end
        return num, 0;
    end
end

function _M:CreateItem(index,itemObj)
    if self.ContentItems[index] then
        return
    end
    local item = self.UIExplorShopItem.New()
    self.ContentItems[index] = item
    item:OnCreate(itemObj,self)
end

-- 隐藏
function _M:OnDisable()

end

-- 卸载
function _M:OnDestroy()
    self:removeEvent();
    if self.ContentItems then
        for key, value in pairs(self.ContentItems) do
            value:OnDestroy()
        end
        self.ContentItems = {}
    end
    self.itemConfig = nil;
    self.hasInit = false
end

-- item类
_M.UIExplorShopItem = Class("UIExplorShopItem",UIComponentInterface)
local _M_T = _M.UIExplorShopItem
function _M_T:OnCreate(obj,parent)
    self.taskId = 0
    self.parent = parent
    self.fguiObj = obj
    self.isGet = false;

    self.rewardItem = obj:GetChild("Btn_Goods");
    self.txtGoodsName = obj:GetChild("Text_GoodsName");
    self.numLimit = obj:GetChild("Text_Stock");
    self.txtNum = obj:GetChild("Text_Num");
    self.loaderCoin = obj:GetChild("Loader_Coin");
    self.soldOutCtrl = obj:GetController("SoldOut");
    self.buyCtrl = obj:GetController("Buy");

    self.fguiObj.onClick:Add(function ()
        self:ClickReward();
    end);
end
function _M_T:OnShow(itemConfig, bugNum)
    self.config = itemConfig;
    self.bugNum = tonumber(bugNum);
    self:Refresh()
end

function _M_T:Refresh()
    local rewards = decodeJsonStrToTabel(self.config.f_SellingList)
    self.bagItemData = nil;
    local itemConfig = G.dataTable["t_item"];
    local rewardItem = itemConfig[tostring(rewards[1][1])];
    if rewardItem ~= nil then
        self.bagItemData = {};
        self.bagItemData.desc = getLanguage(rewardItem.f_Desc);
        self.bagItemData.icon = rewardItem.f_Icon;
        self.bagItemData.itemModelId = rewardItem.f_itemModelId;
        self.bagItemData.itemType = rewardItem.f_BagType;
        self.bagItemData.name = getLanguage(rewardItem.f_ItemName);
        self.bagItemData.num = rewards[1][2];
        self.bagItemData.quality = rewardItem.f_Quality;
        self.bagItemData.remainCount = tonumber(self.config.f_Limit) - self.bugNum;
    end
    logicMgr.CostManager.RefreshItem(self.rewardItem, rewards[1])
    --  logicMgr.CostManager.RefreshItemList(self.costItemList, decodeJsonStrToTabel(v.f_Reward), nil, {isShowBigNum = true});
    self.canBug = nil
    local costItem = decodeJsonStrToTabel(self.config.f_CostList)
    local engNum = 0;
    --self.costList:RemoveChildrenToPool();
    self.costItemName = nil;
    local noEngMoneyType;
    local noEngMoneyPrice;
    local moneyType;
    local price;
    local excNum = -1;
    --for i = 1, #costItem do
    --    local item = self.costList:AddItemFromPool();
    --    local icon = item:GetChild("icon");
        local costItemId = costItem[1][1];
        local itemConfig = itemConfig[tostring(costItemId)];
        self.loaderCoin.url = EnumConst.AtlasPath.ItemAtlas .. itemConfig.f_Icon;
        self.txtGoodsName.text = self.bagItemData.name --getLanguage(itemConfig.f_ItemName);
        --local num = item:GetChild("num");
        local haveNum = tonumber(logicMgr.ItemManager.getBagNumByTableID(tonumber(costItemId)));
        local costNum = tonumber(costItem[1][2]);
        if haveNum >= costNum then
            local a, b = math.modf(haveNum / costNum);
            if excNum == - 1 or a < excNum then
                moneyType = costItemId;
                price = costNum;
                excNum = a;
            end
            engNum = engNum + 1;
            self.buyCtrl.selectedIndex = 1;
        else
            if self.costItemName == nil then
                self.costItemName = itemConfig.f_ItemName;
            end
            noEngMoneyType = costItemId;
            noEngMoneyPrice = costNum;
            self.buyCtrl.selectedIndex = 0;
        end
        self.txtNum.text = costNum;
    --end
    if engNum == #costItem then
        self.canBug = true;
        if self.bagItemData ~= nil then
            self.bagItemData.monyType = moneyType;
            self.bagItemData.moneyIcon = tostring(moneyType);
            self.bagItemData.price = price;
        end
    else
        if self.bagItemData ~= nil then
            self.bagItemData.monyType = noEngMoneyType;
            self.bagItemData.moneyIcon = tostring(noEngMoneyType);
            self.bagItemData.price = noEngMoneyPrice;
        end
    end
    local limit = tonumber(self.config.f_Limit);
    if limit > 0 then
        local remain = limit - self.bugNum
        if remain < 0 then
            remain = 0
        end
        self.numLimit.text = string.format(getLanguage("ActivityExplorTips12"), remain);
        if self.bugNum >= limit then
            self.soldOutCtrl.selectedIndex = 1;
            self.fguiObj.onClick:Clear();
        else
            self.soldOutCtrl.selectedIndex = 0;
        end
    end
end

function _M_T:OnHide()

end
function _M_T:OnDestroy()
    self.fguiObj.onClick:Clear();
end

function _M_T:ClickReward()
    if self.isGet then
        return;
    end

    if self.canBug == nil then
        UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"),getLanguage(self.costItemName)))
        return;
    end
    if self.bagItemData ~= nil then
        showUI(PanelNames.UIBagItemInfo, self.bagItemData, 5, nil, nil, function(buyNum)
            self.isGet = true;
           -- TAManager.TrackActivityEvent(_M.activeId, EnumConst.ActivityTrack.Exchange, self.config.f_Id)
            ActivityHandler.sendReqActivityDrawRewardMessage({_M.activeId, buyNum, tonumber(self.config.f_Id)});
            self:TimeCall(self.TimeEnd, 100);
        end);
    end
end

function _M_T:TimeEnd()
    self:RemoveTimeCall(self.TimeEnd)
    self.isGet = false;
end

return _M;